#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>

#if defined(LINUX)
#include <unistd.h>  
#include <sys/time.h>
#include <pthread.h>
#include <dirent.h>  
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/reboot.h>
#include <linux/rtnetlink.h>
#include <sys/wait.h>  
#include <errno.h>
#else
#include <io.h>
#include <direct.h>
#include <Iphlpapi.h>
#pragma comment(lib,"iphlpapi.lib") 
#pragma comment(lib,"ws2_32.lib")
#pragma warning(disable:4996)
#define snprintf _snprintf

#include "GpsDataStruct.h"
#endif

#include "Logging.h"
#include "TcpServerClient.h"
#include "ArrayList.h"
#include "ConfigFile.h"
#include "GpsContactDbaAccess.h"
#include "GpsDataStruct.h"
#include "cpool.h"

extern SQL_CONN_POOL * sp;

static int   gIsTcpServerRun = 0 ;
static int   gIsTcpClientRun = 0 ;

//int API_StringToTimeEX(char *strDateStr, time_t &timeData);
//BOOL GetStrFromTime(time_t iTimeStamp, char *pszTime);

int GetTcpServerStatus()
{
	return(gIsTcpServerRun);
}
void StopTcpServer()
{
	gIsTcpServerRun = 0 ;
}
int StartTcpServer(const char *name, unsigned short port, TCPCALLBACK tcpcallback)
{
	TCPHANDLE *arg = NULL;
	if( (arg = (TCPHANDLE *)malloc(sizeof(TCPHANDLE))) == NULL )
	{
		WriteFileLog(LERROR,"申请TCPHANDLE结构内存时出错，创建TCP服务程序失败！");
		return(-1);
	}
	memset(arg,0,sizeof(TCPHANDLE));
	if( ( strlen(name) > 250 ) )
	{
		WriteFileLog(LERROR,"TCP服务名不能大于250字节，创建TCP服务程序失败！");
		free(arg);
		return(-2);
	}
	strcpy(arg->name,name);
	arg->port = port;
	arg->tcpcallback = tcpcallback;
	arg->logcallback = NULL;
	gIsTcpServerRun = 1;

	if( (CreateThreadWithArg(&TcpServerListenThread, (void *)arg)) == 0 )
	{
		WriteFileLog(LERROR,"创建TCP服务线程程序失败！");
		free(arg);
		return(-3);
	}

	return(0);
}

void *TcpServerListenThread(void *param)
{
	char                sport[20];
	TCPHANDLE           arg;
	int                 listenfd;
	socklen_t           addrlen;

	socklen_t           len;
	struct sockaddr_in  client;
	TCPHANDLE           *cliarg = NULL;

	memcpy(&arg,param,sizeof(TCPHANDLE));
	free(param);
	param = NULL;

	snprintf(sport,10,"%u", arg.port);

	if( ( listenfd = Tcp_listen(NULL,sport, &addrlen) ) < 0 )
	{
		WriteFileLog(LERROR,"TCP服务（%s）在端口%u上监听失败，程序退出！", arg.name, arg.port);
		exit(0);
	}
	else
	{
		WriteFileLog(LHINT,"TCP服务（%s）在端口%u上开始监听", arg.name, arg.port);
	}

	SetNonblockSocket(listenfd);

	while( gIsTcpServerRun )
	{
		if( (cliarg = (TCPHANDLE *)malloc(sizeof(TCPHANDLE))) == NULL )
		{
			WriteFileLog(LERROR,"申请TCPHANDLE结构内存时出错，无法响应客户端请求！");
            #if defined(LINUX)
			usleep(1000000);
            #else
			Sleep(1000);
            #endif
			continue;
		}

		memset(cliarg,0,sizeof(TCPHANDLE));

		len = addrlen;
		if( ( cliarg->fd = Accept(listenfd, (struct sockaddr *)&client, &len, &gIsTcpServerRun) ) < 0 )
		{
			WriteFileLog(LERROR,"Accept出错，无法响应客户端请求！");
			free(cliarg);
            #if defined(LINUX)
			usleep(1000000);
            #else
			Sleep(1000);
            #endif
			continue;
		}
		else if( cliarg->fd == 0 )
		{
			WriteFileLog(LERROR,"Accept错误，无法响应客户端请求！");
			free(cliarg);
            #if defined(LINUX)
			usleep(1000000);
            #else
			Sleep(1000);
            #endif
			continue;
		}

		SetSOLINGEROn(cliarg->fd);
		SetNonblockSocket(cliarg->fd);

		cliarg->tcpcallback = arg.tcpcallback;
		strcpy(cliarg->name,arg.name);
		strncpy(cliarg->cip,inet_ntoa(client.sin_addr),19);
		cliarg->cport = ntohs(client.sin_port);

		if( (CreateThreadWithArg(&TcpServerConnectThread, (void *)cliarg)) == 0 )
		{
			WriteFileLog(LERROR,"TCP服务端应答客户端（%s:%u）线程创建失败，创建TCP服务程序失败！",cliarg->cip,cliarg->cport);
			shutdown(cliarg->fd,2); 
			Close(cliarg->fd);
			free(cliarg);
            #if defined(LINUX)
			usleep(1000000);
            #else
			Sleep(1000);
            #endif
			continue;
		}
	}
	Close(listenfd);
	WriteFileLog(LHINT,"TCP服务（%s）结束在端口%u上的监听服务", arg.name, arg.port);
	return(0);
}

void *TcpServerConnectThread(void *param)
{
	TCPHANDLE  arg;
	memcpy(&arg,param,sizeof(TCPHANDLE));
	free(param);
	param = NULL;

	if( arg.tcpcallback != NULL )
	{
		arg.tcpcallback(arg.name,arg.fd,arg.cip,arg.cport);
	}

	shutdown(arg.fd,2); 
	Close(arg.fd);
	return(NULL);
}

//void TcpSocketServerInterface(int sockfd,char *ip,int port)
//{
//    int          n;
//    char         buf[20480];
//    
//    memset(buf,0,sizeof(buf));
//
//    WriteFileLog(LHINT,"Tcp socket connect from %s:%d socket is %d, has connected.",ip,port,sockfd);
//    
//again:
//
//    while( (n = recv(sockfd, buf, 20400,0)) > 0 )
//    {
//        WriteFileLog(LDEBUG,"%ld bytes is received : '%s'",n,buf);
//    }
//    #if defined(LINUX)
//    if( n < 0 && ( errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN ) )
//    #else
//    if( n < 0 && ( errno == EINTR || errno == WSAEWOULDBLOCK || errno == EAGAIN ) )
//    #endif
//    {
//        WriteFileLog(LERROR,"Tcp socket recv timeout , read again.");
//        goto again;
//    }
//    else if( n == 0 )
//    {
//        WriteFileLog(LHINT,"Received a closed requests from the client.");
//    }
//    else
//    {
//        WriteFileLog(LERROR,"Websocket parsing errors, n=%d,   the client disconnects.",n);
//    }
//    WriteFileLog(LHINT,"Disconnect a Tcp socket connection from %s:%d socket is %d",ip,port,sockfd);
//}
//
//void TcpSocketServerCallback(char *name, int fd, char *ip, unsigned short port)
//{
//	int            n;
//	char           cz[10240],buf[10240];
//
//    WriteFileLog(LHINT,"Tcp socket connect from %s:%u socket is %d, has connected.",ip,port,fd);
//
//again:
//
//    while( (n = recv(fd, buf, 10000,0)) > 0 )
//	{
//		buf[n] = '\0';
//		HexToString(buf, n, cz, 10000);
//		WriteFileLog(LHINT,"收到指令：'%s'(%d:%s)",buf,n,cz);
//	}
//    #if defined(LINUX)
//	if( n < 0 && ( errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN ) )
//	{
//		usleep(1000);
//		if( GetTcpServerRun() )
//		{
//			goto again;
//		}
//		else
//		{
//			WriteFileLog(LERROR,"Tcp服务器关闭监听！");
//		}
//	}
//	else if( ( n == -1 ) && ( errno == 104 ) )
//	{
//		WriteFileLog(LERROR,"Tcp客户端（%s:%u）关闭连接",ip,port);
//	}
//	else
//	{
//		WriteFileLog(LERROR,"Tcp客户端（%s:%u）通讯错误！",ip,port);
//	}
//    #else
//	int err = WSAGetLastError();
//	if( err == WSAEWOULDBLOCK ) 
//	{
//		Sleep(1);
//		if( GetTcpServerRun() )
//		{
//			goto again;
//		}
//		else
//		{
//			WriteFileLog(LERROR,"Tcp服务器关闭监听！");
//		}
//	}
//	else if( err == WSAESHUTDOWN ) 
//	{
//		WriteFileLog(LERROR,"Tcp客户端（%s:%u）关闭连接",ip,port);
//	}
//	else
//	{
//		WriteFileLog(LERROR,"Tcp客户端（%s:%u）通讯错误！",ip,port);
//	}
//    #endif
//
//    WriteFileLog(LHINT,"Tcp socket connect from %s:%u socket is %d, has Disconnected.",ip,port,fd);
//}
//
//void TcpSocketServerDisplayCallback(int level, char *message)
//{
//	WriteFileLog(__LINE__, __FILE__, level, message);
//}
//

void DisplayClientInfo(ARRAYLIST *lst);
void TcpSocketInterface(char *name, int fd, char *ip, unsigned short port)
{
    int          n,len;
    char         buf[10240];

    int          isLogin;
    long         num;
	char         *revbuf[14] = { 0 }; //存放分割后的子字符串 
	int          splitcount = 0;		      //分割后子字符串的个数
	char         parambuf[1000];
	char         *tmpbuf1;   //在split前先替换连续的逗号
	char         *tmpbuf2;
	char         s1[3] = ",,"; //替换前内容
	char         s2[4] = ", ,";//替换后内容
	char         sGNRMC[6] = "GNRMC"; //GPS4设备需要排除的异常字符串
    char         czTemp[10240];
    char         czCmd[300],czName[300],czUser[300],czPass[300];
	char         czTime[50],czLatitude[50],czLatitudeH[10],czLongitude[50],czLongitudeH[10],czSpeed[50],czCourse[50],czMileage[50];
	char         cname[20];  //temp
	char         accessUser2[50] = "admin";
	char         accessPass2[50] = "admin";
	/*time_t time;
	struct tm *info;*/

	memset(cname, 0, 20);   //temp
    memset(buf,0,sizeof(buf));

    num = 0;
    isLogin = 0;

    if( ArrayListInsert(&al,fd,name,ip,port) == 1 )
    {
        WriteFileLog(LHINT,"The tcp client connect from %s:%u socket is %d, connection is successful.",ip,port,fd);
    }
    else
    {
        WriteFileLog(LERROR,"The tcp client connect from %s:%u socket is %d, connection is failure.",ip,port,fd);
        return;
    }
//isLogin = 1;
   //isInMatch = 1;
	//isLogin = 1;
	//isInMatch = 0;   //临时，全设为比赛开始
	ArrayListDisplay(&al, &DisplayClientInfo);

//again:

    //返回 >0 : 正常
    //返回  0 : 对方关闭连接
    //返回 -1 : socket读取错误 
    //返回 -2 : 本方关闭连接 
    //返回 -3 : 读取的字符串超长 
    while( (n = TcpSocketRead(fd,buf,&len,10000,&gIsTcpServerRun)) > 0 )
    {
        ArrayListUpdateActive(&al,fd);
		WriteFileLog(LHINT, buf);
		if(strstr(buf, sGNRMC))//如果找到了这个龟龟字符串
		{
			WriteFileLog(LERROR, "guigui string lai le GNRMC tiaoguo (%s:%u).", ip, port);
			break;
		}

        if( len > 4096 )
        {
            WriteFileLog(LERROR,"Receive tcp string more than 4096 characters, receive instructions to ignore .");
            n = -8;
			//发送失败指令
			memset(czTemp, 0, sizeof(czTemp));
			sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
			if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
			{
				WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
				shutdown(fd, 2);
				Close(fd);
			}
            break;
        }

        memset(czTemp,0,sizeof(czTemp));
        memset(czName,0,sizeof(czName));
        if( GetSubstr(buf,"\"Command\":",",",czTemp,256) < 0 )
        {
            if( GetSubstr(buf,"\"Command\":","}",czTemp,256) < 0 )
            {
                WriteFileLog(LERROR,"Command field parsing error , the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }
        }
        if( GetSubstr(czTemp,"\"","\"",czCmd,256) < 0 )
        {
            WriteFileLog(LERROR,"Command field parsing error , the client disconnects.");
            n = -8;
			//发送失败指令
			memset(czTemp, 0, sizeof(czTemp));
			sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
			if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
			{
				WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
				shutdown(fd, 2);
				Close(fd);
			}
            break;
        }

        if( strcmp(czCmd,"GPS_LOGIN") == 0 )
        {
            WriteFileLog(LHINT,"Receive GPS_LOGIN form client(%s:%u).",ip,port);

            /*if( isLogin == 1 )
            {
                WriteFileLog(LERROR,"Received repeat login command, the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }*/

            memset(czTemp,0,sizeof(czTemp));
            memset(czName,0,sizeof(czName));
            if( GetSubstr(buf,"\"Name\":",",",czTemp,256) < 0 )
            {
                WriteFileLog(LERROR,"Name field parsing error , the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }
            if( GetSubstr(czTemp,"\"","\"",czName,256) < 0 )
            {
                WriteFileLog(LERROR,"Name field parsing error , the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }
            if( strlen(czName) <= 0 )
            {
                WriteFileLog(LERROR,"Name field can not be empty , the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }
			strcpy(cname, czName);  //temp
            memset(czTemp,0,sizeof(czTemp));
            memset(czUser,0,sizeof(czUser));
            if( GetSubstr(buf,"\"Userid\":",",",czTemp,256) < 0 )
            {
                WriteFileLog(LERROR,"Userid field parsing error , the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }
            if( GetSubstr(czTemp,"\"","\"",czUser,256) < 0 )
            {
                WriteFileLog(LERROR,"Userid field parsing error , the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }
            if( strlen(czUser) <= 0 )
            {
                WriteFileLog(LERROR,"Userid field can not be empty , the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }

            memset(czTemp,0,sizeof(czTemp));
            memset(czPass,0,sizeof(czPass));
            if( GetSubstr(buf,"\"Password\":","}",czTemp,256) < 0 )
            {
                WriteFileLog(LERROR,"Password field parsing error , the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }
            if( GetSubstr(czTemp,"\"","\"",czPass,256) < 0 )
            {
                WriteFileLog(LERROR,"Password field parsing error , the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }
            if( strlen(czPass) <= 0 )
            {
                WriteFileLog(LERROR,"Password field can not be empty , the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }

			if( ( strcmp(czUser,accessUser2) != 0 ) || ( strcmp(czPass,accessPass2) != 0 ) )
			{
                WriteFileLog(LERROR,"User login validation error , the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
			}
			isLogin = 1;
			//登录成功，发送成功指令
			memset(czTemp, 0, sizeof(czTemp));
			sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"1\"}");  //成功指令
			if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
			{
				WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
				shutdown(fd, 2);
				Close(fd);
			}
			else
			{
				//WriteFileLog(LDEBUG, "Send succeed to tcp client(%s:%u) successfully.", ip, port);
			}
            /*if( ArrayListUpdateLogin(&al,fd,czName,isSamename) == 1 )
            {
                isLogin = 1;
                WriteFileLog(LHINT,"The tcp client(%s) login successfully.",czName);
            }
            else
            {
                WriteFileLog(LERROR,"The tcp client(%s) login failure.",czName);
                n = -8;
                break;
            }
            ArrayListDisplay(&al,&DisplayClientInfo);*/
        }
        else if( strcmp(czCmd,"PING") == 0 )
        {
            WriteFileLog(LHINT,"Receive PING form client(%s:%u).",ip,port);
            memset(czTemp,0,sizeof(czTemp));
            sprintf(czTemp,"{\"Name\":\"PONG\"}");
            if( TcpSocketWrite(fd,czTemp,strlen(czTemp)) <= 0 )
            {
                WriteFileLog(LERROR,"Send PONG to tcp client(%s:%u) failure.",ip,port);
                shutdown(fd,2); 
                Close(fd);
            }
            else
            {
                WriteFileLog(LDEBUG,"Send PONG to tcp client(%s:%u) successfully.",ip,port);
            }
        }
        else if( strcmp(czCmd,"GPS_EXIT") == 0 )
        {
            WriteFileLog(LHINT,"Receive GPS_EXIT form client(%s:%u), the client disconnects.",ip,port);
            n = 0;
            break;
        }
		else if (strcmp(czCmd, "GPS_MATCH_START") == 0)
		{
			memset(czTemp, 0, sizeof(czTemp));
			memset(czName, 0, sizeof(czName));
			if (GetSubstr(buf, "\"MatchName\":", "}", czTemp, 256) < 0)
			{
				WriteFileLog(LERROR, "第一个 MatchId field parsing error , the client disconnects.");
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //失败指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send error to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
				else
				{
					//WriteFileLog(LDEBUG, "Send error to tcp client(%s:%u) successfully.", ip, port);
				}
				n = -8;
				break;
			}
			if (GetSubstr(czTemp, "\"", "\"", czName, 256) < 0)
			{
				WriteFileLog(LERROR, "第二个 MatchId field parsing error , the client disconnects.");
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //失败指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send error to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
				else
				{
					//WriteFileLog(LDEBUG, "Send error to tcp client(%s:%u) successfully.", ip, port);
				}
				n = -8;
				break;
			}
			if (strlen(czName) <= 0)
			{
				WriteFileLog(LERROR, "MatchId field can not be empty , the client disconnects.");
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //失败指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send error to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
				else
				{
					//WriteFileLog(LDEBUG, "Send error to tcp client(%s:%u) successfully.", ip, port);
				}
				n = -8;
				break;
			}

			//matchId = atoi(czName);
			strcpy(matchName, czName);
			isInMatch = 1;
			WriteFileLog(LDEBUG, "GPS match(%d) started!", matchId);
			//获取比赛ID
			int matchid = -1;
			int param = 1;
			SQL_NODE *mynode  = get_db_connect(sp);
			if(NULL == mynode)
			{
				WriteFileLog(LERROR, "获取比赛id时，没有取到数据库连接！");
				param = 0;
			}
			matchid = GetIdWithMatchName(&(mynode->fd), matchName);
			if(-1 == matchid)
			{
				WriteFileLog(LERROR, "获取比赛id时，没有取得可用id！");
				param = 0;
			}
			matchId = matchid;
			release_node(sp,mynode);
			
			sprintf(czTemp, "{\"Command\":\"GPS_MATCH_START\",\"Param\":\"%d\"}",param);  //返回指令
			if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
			{
				WriteFileLog(LERROR, "Send retMsg to tcp client(%s:%u) failure.", ip, port);
				shutdown(fd, 2);
				Close(fd);
			}
			else
			{
				//WriteFileLog(LDEBUG, "Send retMsg to tcp client(%s:%u) successfully.", ip, port);
			}
		}

		else if (strcmp(czCmd, "GPS_MATCH_STATE") == 0)//查询比赛状态
		{
printf("state\n");
			memset(czTemp, 0, sizeof(czTemp));
			memset(czName, 0, sizeof(czName));
			if (GetSubstr(buf, "\"MatchName\":", "}", czTemp, 256) < 0)
			{
				WriteFileLog(LERROR, "第一个 MatchId field parsing error , the client disconnects.");
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //失败指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send error to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
				else
				{
					//WriteFileLog(LDEBUG, "Send error to tcp client(%s:%u) successfully.", ip, port);
				}
				n = -8;
				break;
			}
			if (GetSubstr(czTemp, "\"", "\"", czName, 256) < 0)
			{
				WriteFileLog(LERROR, "第二个 MatchId field parsing error , the client disconnects.");
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //失败指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send error to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
				else
				{
					//WriteFileLog(LDEBUG, "Send error to tcp client(%s:%u) successfully.", ip, port);
				}
				n = -8;
				break;
			}
			if (strlen(czName) <= 0)
			{
				WriteFileLog(LERROR, "MatchId field can not be empty , the client disconnects.");
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //失败指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send error to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
				else
				{
					//WriteFileLog(LDEBUG, "Send error to tcp client(%s:%u) successfully.", ip, port);
				}
				n = -8;
				break;
			}

			int param = isInMatch;

			sprintf(czTemp, "{\"Command\":\"GPS_STATE_RETURN\",\"Param\":\"%d\"}", param);  //返回指令
			if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
			{
				WriteFileLog(LERROR, "Send retMsg to tcp client(%s:%u) failure.", ip, port);
				shutdown(fd, 2);
				Close(fd);
			}
			else
			{
				//WriteFileLog(LDEBUG, "Send retMsg to tcp client(%s:%u) successfully.", ip, port);
			}
		}
		else if (strcmp(czCmd, "GPS_MATCH_CURRENT") == 0)	//查询当前比赛信息
		{
			printf("state\n");
			memset(czTemp, 0, sizeof(czTemp));
			//unsigned short matchId;                          // 比赛Id
			//char           matchName[50];                    // 比赛名
			//unsigned short isInMatch;                        // 是否在比赛中，0：非比赛，1：比赛中
			// 返回一个 比赛Id 比赛名字
			if (isInMatch)
			{
				sprintf(czTemp, "{\"Command\":\"GPS_MATCH_CURRENT\",\"Param\":\"%d|%s\"}", matchId, matchName);  //返回指令
			}
			else {
				sprintf(czTemp, "{\"Command\":\"GPS_MATCH_CURRENT\",\"Param\":\"%d|\"}", 0);  //返回指令
			}

			if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
			{
				WriteFileLog(LERROR, "Send retMsg to tcp client(%s:%u) failure.", ip, port);
				shutdown(fd, 2);
				Close(fd);
			}
			else
			{
				//WriteFileLog(LDEBUG, "Send retMsg to tcp client(%s:%u) successfully.", ip, port);
			}
		}

		else if (strcmp(czCmd, "GPS_MATCH_END") == 0)
		{
			isInMatch = 0;
			WriteFileLog(LDEBUG, "GPS match(%d) ended!", matchId);
            memset(czTemp, 0, sizeof(czTemp));
            sprintf(czTemp, "{\"Command\":\"GPS_MATCH_END\",\"Param\":\"%d\"}",1);  //返回指令
			if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
			{
				WriteFileLog(LERROR, "Send retMsg to tcp client(%s:%u) failure.", ip, port);
				shutdown(fd, 2);
				Close(fd);
			}
			else
			{
				//WriteFileLog(LDEBUG, "Send retMsg to tcp client(%s:%u) successfully.", ip, port);
			}
		}
else if(strcmp(czCmd, "GPS_GSV") == 0)
{
}
        else
        {
            if( isLogin == 0 )
            {
                WriteFileLog(LERROR,"The tcp client has not logged in,  the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }

            if( strcmp(czCmd,"GPS_DATA") != 0 )
            {
                WriteFileLog(LDEBUG,"From tcp client(%s) received(%d:'%s')",czName,strlen(buf),buf);
            }

			memset(czTemp,0,sizeof(czTemp));
            memset(czName,0,sizeof(czName));
            if( GetSubstr(buf,"\"Name\":",",",czTemp,256) < 0 )
            {
                WriteFileLog(LERROR,"Name field parsing error , the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }
            if( GetSubstr(czTemp,"\"","\"",czName,256) < 0 )
            {
                WriteFileLog(LERROR,"Name field parsing error , the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }
            if( strlen(czName) <= 0 )
            {
                WriteFileLog(LERROR,"Name field can not be empty , the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }
			
			memset(parambuf, 0, sizeof(parambuf));
            memset(czTemp,0,sizeof(czTemp));
            /*memset(czTime,0,sizeof(czTime));
            memset(czLatitude,0,sizeof(czLatitude));
            memset(czLatitudeH,0,sizeof(czLatitudeH));
            memset(czLongitude,0,sizeof(czLongitude));
            memset(czLongitudeH,0,sizeof(czLongitudeH));
            memset(czSpeed,0,sizeof(czSpeed));
            memset(czCourse,0,sizeof(czCourse));
            memset(czMileage,0,sizeof(czMileage));*/
            if( GetSubstr(buf,"\"Param\":","}",czTemp,800) < 0 )
            {
                WriteFileLog(LERROR,"Param field parsing error , the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }
            if( GetSubstr(czTemp,"\"","\"", parambuf,800) < 0 )
            {
                WriteFileLog(LERROR,"Param field parsing error , the client disconnects.");
                n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
                break;
            }
			
			tmpbuf1 = replace(parambuf, s1, s2);
			tmpbuf2 = replace(tmpbuf1,s1,s2);
			if (Split(tmpbuf2, ",", revbuf, &splitcount)) //调用函数进行分割 
			//if (Split(parambuf, ",", revbuf, &splitcount)) //调用函数进行分割 
			{
				//字符串分割出错
				WriteFileLog(LERROR, "split string error , the client disconnects.");
				n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					free(tmpbuf1);
					free(tmpbuf2);
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
				break;
			}
                        /*WriteFileLog(LDEBUG, "分割后是%d 项", splitcount);
			int ii = 0;
			for (ii; ii < splitcount; ii++)
			{
				if(revbuf[ii]!=NULL)
					WriteFileLog(LDEBUG, "revbuf[%d] is %s ", ii, revbuf[ii]);
			}*/
			if (splitcount != 13)
			{
				//分割后不是13项数据
				WriteFileLog(LERROR, "recv string mismatching , the client disconnects.");
				n = -8;
				//发送失败指令
				memset(czTemp, 0, sizeof(czTemp));
				sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"0\"}");  //指令
				if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
				{
					WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
					shutdown(fd, 2);
					Close(fd);
				}
				free(tmpbuf1);
				free(tmpbuf2);
				break;
			}
			//接收正常，发送成功指令
			memset(czTemp, 0, sizeof(czTemp));
			sprintf(czTemp, "{\"Command\":\"GPS_RETURN\",\"Param\":\"1\"}");  //成功指令
			if (TcpSocketWrite(fd, czTemp, strlen(czTemp)) <= 0)
			{
				WriteFileLog(LERROR, "Send succeed to tcp client(%s:%u) failure.", ip, port);
				shutdown(fd, 2);
				Close(fd);
			}
			else
			{
				//WriteFileLog(LDEBUG, "Send succeed to tcp client(%s:%u) successfully.", ip, port);
			}
			/*
			revbuf[0];  //$GPRMC
			revbuf[1];  //UTC时间，hhmmss（时分秒）格式
			revbuf[2];  //定位状态，A=有效定位，V=无效定位
			revbuf[3];  //纬度ddmm.mmmm（度分）格式（前面的0也将被传输）
			revbuf[4];  //纬度半球N（北半球）或S（南半球）
			revbuf[5];  //经度dddmm.mmmm（度分）格式（前面的0也将被传输）
			revbuf[6];  //经度半球E（东经）或W（西经）
			revbuf[7];  //地面速率（000.0~999.9节，前面的0也将被传输）
			revbuf[8];  //地面航向（000.0~359.9度，以真北为参考基准，前面的0也将被传输）
			revbuf[9];  //UTC日期，ddmmyy（日月年）格式
			revbuf[10]; //磁偏角（000.0~180.0度，前面的0也将被传输）
			revbuf[11]; //磁偏角方向，E（东）或W（西）
			revbuf[12]; //模式指示（仅NMEA0183 3.00版本输出，A=自主定位，D=差分，E=估算，N=数据无效) <12>*hh<CR><LF>
			*/


			if (isInMatch == 1)
			{
#if defined(LINUX)
				GpsDataStruct* tp = (GpsDataStruct*)malloc(sizeof(GpsDataStruct));
				sprintf(tp->czName, "%s", czName);
				sprintf(tp->czTime, "%s", revbuf[1]);
				sprintf(tp->czLatitude, "%s", revbuf[3]);
				sprintf(tp->czLatitudeH, "%s", revbuf[4]);
				sprintf(tp->czLongitude, "%s", revbuf[5]);
				sprintf(tp->czLongitudeH, "%s", revbuf[6]);
				sprintf(tp->czSpeed, "%s", revbuf[7]);
				sprintf(tp->czCourse, "%s", revbuf[8]);
				//sprintf(tp->czMileage, "%s", czMileage);
			if (PushGpsData(tp) == -1)
			{
				WriteFileLog(LERROR, "Add GpsDataStruct error!");
			}
			else
				WriteFileLog(LHINT, "Add GpsDataStruct succeed !");
#endif
			}
			free(tmpbuf1);
			free(tmpbuf2);
        }
    }
    if( n == -8 )
    {
        WriteFileLog(LERROR,"Synchronous communication error, the server disconnects the client's active connection.");
    }
    else if( n == -3 )
    {
        WriteFileLog(LHINT,"Received a long tcp string, the client disconnects.");
    }
    else if( n == -2 )
    {
        WriteFileLog(LERROR,"The server disconnects the client's active connection.");
    }
    else if( n == -1 )
    {
        WriteFileLog(LERROR,"Tcp read errors, the client disconnects.");
    }
    else if( n == 0 )
    {
        WriteFileLog(LHINT,"Received a closed requests from the client.");
    }
    else
    {
        WriteFileLog(LERROR,"Tcp parsing errors, n=%d,   the client disconnects.",n);
    }

    if( isLogin == 1 )
    {
        if( ArrayListDeleteByFD(&al,fd) != 1 )
        {
            WriteFileLog(LERROR,"Deleted the client(%d) from ArrayList error, the client is not logged in.",fd);
        }
        else
        {
            WriteFileLog(LHINT,"Deleted the client(%d) from ArrayList success.",fd);
        }
    }
    ArrayListDisplay(&al,&DisplayClientInfo);
    WriteFileLog(LHINT,"Disconnect a tcp connection(%s) from %s:%d socket is %d",name,ip,port,fd);
}

void DisplayClientInfo(ARRAYLIST *lst)
{
	size_t i;
    WriteFileLog(LHINT,"ToTal client list is %ld",lst->num);
    for(i=0;i<lst->num;i++)
    {
        double t1 = GetTimeVal();
        WriteFileLog(LHINT,"ClientList(%02d) FD=%d Name=%s ip=%s port=%u logined=%d time=%.2lf",i,lst->data[i].fd,lst->data[i].name,lst->data[i].ip,lst->data[i].port,lst->data[i].logined,t1-lst->data[i].activetime);
    }

}

int GetTcpClientStatus()
{
	return(gIsTcpClientRun);
}

void StopTcpClient()
{
	gIsTcpClientRun = 0 ;
}

int StartTcpClient(const char *name,const char *host, unsigned short port, TCPCALLBACK tcpcallback, LOGCALLBACK logcallback)
{
	TCPHANDLE *arg = NULL;
	if( (arg = (TCPHANDLE *)malloc(sizeof(TCPHANDLE))) == NULL )
	{
		if( logcallback != NULL )
		{
			logcallback(LEVEL_ERROR,"A memory application error occurred when creating the TCP client.");
		}
		return(-1);
	}
	memset(arg,0,sizeof(TCPHANDLE));
	if( ( strlen(name) > 250 ) )
	{
		if( logcallback != NULL )
		{
			logcallback(LEVEL_ERROR,"The name of the TCP client cannot exceed 250 characters.");
		}
		free(arg);
		return(-2);
	}
	strcpy(arg->name,name);
	if( ( strlen(host) > 16 ) )
	{
		if( logcallback != NULL )
		{
			logcallback(LEVEL_ERROR,"The host of the TCP client cannot exceed 16 characters.");
		}
		free(arg);
		return(-3);
	}
	strcpy(arg->host,host);

	arg->port = port;
	strcpy(arg->cip,arg->host);
	arg->cport = port;
	arg->tcpcallback = tcpcallback;
	arg->logcallback = logcallback;
	gIsTcpClientRun = 1;

	if( (CreateThreadWithArg(&TcpClientConnectThread, (void *)arg)) == 0 )
	{
		if( logcallback != NULL )
		{
			logcallback(LEVEL_ERROR,"When the TCP client is created, the thread creates an error.");
		}
		free(arg);
		return(-5);
	}

	return(0);
}

void *TcpClientConnectThread(void *param)
{
	char      sport[20];
	char      msg[10240];
	TCPHANDLE arg;
	memcpy(&arg,param,sizeof(TCPHANDLE));
	free(param);
	param = NULL;

	snprintf(sport,10,"%u",arg.port);

	//if( (CreateThreadWithArg(&TcpClientHeartbeatThread, (void *)&arg)) == 0 )
	//{
	//	snprintf(msg,10000,"Create tcp client(%s) heartbeat thread failure, CreateThreadWithArg error.",arg.name);
	//	if( arg.logcallback != NULL )
	//	{
	//		arg.logcallback(LEVEL_ERROR,msg);
	//	}
	//}

	while( gIsTcpClientRun )
	{
		if( ( arg.fd = Tcp_connect(arg.host,sport) ) < 0 )
		{
			snprintf(msg,10000,"Tcp client(%s) connect %s:%u failure.",arg.name,arg.host,arg.port);
			if( arg.logcallback != NULL )
			{
				arg.logcallback(LEVEL_ERROR,msg);
			}
            #if defined(LINUX)
			usleep(100000);
            #else
			Sleep(100);
            #endif
			continue;
		}
		else
		{
			snprintf(msg,10000,"Tcp client(%s) connect %s:%u success.",arg.name,arg.host,arg.port);
			if( arg.logcallback != NULL )
			{
				arg.logcallback(LEVEL_HINT,msg);
			}
		}

		SetSOLINGEROn(arg.fd);
		SetNonblockSocket(arg.fd);

		if( arg.tcpcallback != NULL )
		{
			arg.tcpcallback(arg.name,arg.fd,arg.cip,arg.cport);
		}

		shutdown(arg.fd,2); 
		Close(arg.fd);

		snprintf(msg,10000,"Tcp client(%s) disconnect %s:%u",arg.name,arg.host,arg.port);
		if( arg.logcallback != NULL )
		{
			arg.logcallback(LEVEL_HINT,msg);
		}
		else
		{
			WriteFileLog(LHINT,msg);
		}

	}

	snprintf(msg,10000,"The tcp connection between client(%s) and server(%s:%u) has been disconnected.",arg.name,arg.host,arg.port);
	if( arg.logcallback != NULL )
	{
		arg.logcallback(LEVEL_HINT,msg);
	}
	else
	{
		WriteFileLog(LHINT,msg);
	}

    #if defined(LINUX)
	sleep(3);
    #else
	Sleep(3000);
    #endif

	return(0);

}

//static void *TcpClientHeartbeatThread(void *param)
//{
//	char      cz3[1024],cz4[1024];
//	typedef   void (*logcallback)(int level, char *message);
//
//	TCPHANDLE *arg = (TCPHANDLE *)param;
//	logcallback callback = arg->logcallback;
//
//	snprintf(cz3,1000,"{\"Command\":\"PING\"}");
//	snprintf(cz4,1000,"Tcp client(%s) on %s:%s, send heartbeat failure.",arg->name,arg->host,arg->port);
//
//	while( gIsTcpClientRun )
//	{
//		if( arg->fd && arg->connected  )
//		{
//			if( TcpSocketWrite(arg->fd, cz3, strlen(cz3)) <= 0 ) 
//			{
//				if( callback != NULL )
//				{
//					callback(LEVEL_ERROR,cz4);
//				}
//				else
//				{
//					WriteFileLog(LERROR,cz4);
//				}
//			}
//		}
//        #if defined(LINUX)
//		sleep(3);
//        #else
//		Sleep(3000);
//        #endif
//	}
//	return(0);
//
//}



//static void TcpSocketClientInterface(char *name,int fd,int *loop)
//{
//	int            n,len;
//	TCPBUFFER      tcpbuf;
//	char           buf[10240],cz[10240];
//	char           czName[1024],str[1024];
//
//	memset(cz,0,sizeof(cz));
//	memset(buf,0,sizeof(buf));
//
//	WriteFileLog(LHINT,"Tcp客户端（%s），连接服务器成功！",name);
//
//	tcpbuf.read_cnt = 0 ;
//	tcpbuf.read_ptr = tcpbuf.read_buf;
//	
//	sprintf(buf,"{\"Name\":\"LOGIN\",\"Receiver\":\"%s\",\"Depart\":\"%s\",\"Param\":\"Display\"}",name,"测试应用");
//	memset(cz,0,sizeof(cz));
//	GB18030ToUTF_8(buf,strlen(buf),cz,&len);
//	if( TcpSocketWrite(fd,cz,len) <= 0 )
//	{
//		sprintf(str,"Tcp客户端（%s），发送登陆请求失败，客户端退出！",name);
//		errorList->AddString(str);
//		errorList->SetCurSel(errorList->GetCount()-1);
//		WriteFileLog(LERROR,str);
//		return;
//	}
//	else
//	{
//		sprintf(str,"Tcp客户端（%s），发送登陆请求成功！",name);
//		pList->AddString(str);
//		pList->SetCurSel(pList->GetCount()-1);
//		WriteFileLog(LHINT,str);
//		pConnect->EnableWindow(FALSE);
//		pDisconnect->EnableWindow(TRUE);
//	}
//
//again:
//
//    //返回 >0 : 正常
//    //返回  0 : 连接关闭
//    //返回 -1 : socket读取错误 
//    //返回 -2 : 接收字符超长
//    while( (n = TcpSocketRead(fd,cz,&len,10000,&tcpbuf)) > 0 )
//	{
//		int len1;
//		UTF_8ToGB18030(cz,strlen(cz),buf,&len1);
//
//		memset(cz,0,sizeof(cz));
//		if( GetSubstr(buf,"\"Name\":",",",cz,256) < 0 )
//		{
//    	    sprintf(str,"Name field parsing error , the client disconnects.");
//            errorList->AddString(str);
//            errorList->SetCurSel(errorList->GetCount()-1);
//    		WriteFileLog(LERROR,str);
//			n = 0;
//			break;
//		}
//		else
//		{
//			if( GetSubstr(cz,"\"","\"",cz,256) < 0 )
//			{
//			    sprintf(str,"Name field more than 256 characters , the client disconnects.");
//  		        errorList->AddString(str);
//                errorList->SetCurSel(errorList->GetCount()-1);
//				WriteFileLog(LERROR,str);
//				n = 0;
//				break;
//			}
//		}
//
//		if( strcmp(czName,"PING") == 0 )
//		{
//			sprintf(str,"Received PING!");
//			pList->AddString(str);
//			pList->SetCurSel(pList->GetCount()-1);
//			WriteFileLog(LHINT,str);
//		}
//		else
//		{
//			sprintf(str,"接收到意外指令：'%s'",buf);
//			errorList->AddString(str);
//			errorList->SetCurSel(errorList->GetCount()-1);
//			WriteFileLog(LHINT,str);
//		}
//	}
//    #if defined(LINUX)
//    if( n < 0 && ( errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN ) )
//    #else
//    if( n < 0 && ( errno == EINTR || errno == WSAEWOULDBLOCK || errno == EAGAIN ) )
//    #endif
//	{
//        WriteFileLog(LERROR,"Tcp socket receive timeout , read again.");
//		goto again;
//	}
//	else if( n == -8 )
//	{
//    	sprintf(str,"通讯同步错误，出于安全考虑，服务器主动断开客户端(%s)的连接！",name);
//	    errorList->AddString(str);
//        errorList->SetCurSel(errorList->GetCount()-1);
//		WriteFileLog(LERROR,str);
//	}
//	else if( n == -2 )
//	{
//    	sprintf(str,"客户端接收到超长指令，客户端(%s)断开连接！",name);
//	    errorList->AddString(str);
//        errorList->SetCurSel(errorList->GetCount()-1);
//		WriteFileLog(LERROR,str);
//	}
//	else if( n == -1 )
//	{
//    	sprintf(str,"Socket通讯错误，客户端(%s)断开连接！",name);
//	    errorList->AddString(str);
//        errorList->SetCurSel(errorList->GetCount()-1);
//		WriteFileLog(LERROR,str);
//	}
//	else if( n == 0 )
//	{
//    	sprintf(str,"客户端接收到关闭请求，客户端(%s)断开连接。",name);
//	    pList->AddString(str);
//        pList->SetCurSel(pList->GetCount()-1);
//		WriteFileLog(LHINT,str);
//	}
//	else
//	{
//    	sprintf(str,"客户端出现意外错误（%s），客户端断开连接！",strerror(errno));
//	    errorList->AddString(str);
//        errorList->SetCurSel(errorList->GetCount()-1);
//		WriteFileLog(LERROR,str);
//	}
//
//	pConnect->EnableWindow(TRUE);
//	pDisconnect->EnableWindow(FALSE);
//	WriteFileLog(LHINT,"Tcp客户端（%s），与服务器已经断开连接！",name);
//}

//void TcpSocketClientCallback(char *name, int fd, char *ip, unsigned short port)
//{
//	int            n,len;
//	char           cz[1024],buf[10240];
//
//	//memset(cz,0,sizeof(cz));
//	//memset(buf,0,sizeof(buf));
//
//	socketFd = fd;
//
//	if( LiveWireWrite("LOGIN") < 0 )
//	{
//		WriteFileLog(LERROR,"LiveWire协议测试客户端登陆失败！");
//		socketFd = 0;
//		return;
//	}
//	else
//	{
//		WriteFileLog(LHINT,"LiveWire协议测试客户端登陆成功！");
//	}
//
//	if( hMainWnd )
//	{
//		::SendMessage(hMainWnd,WM_DISCONNECT_ENABLE,0,0); 
//	}
//
//again:
//
//    while( (n = recv(fd, buf, 10000,0)) > 0 )
//	{
//		StringToHex(buf, strlen(buf), cz, 1024);
//		WriteFileLog(LHINT,"收到指令：%s(%s)",buf,cz);
//	}
//    #if defined(LINUX)
//	if( n < 0 && ( errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN ) )
//	{
//		usleep(1000);
//		if( GetTcpClientRun() )
//		{
//			goto again;
//		}
//		else
//		{
//			WriteFileLog(LERROR,"服务器关闭连接！");
//		}
//	}
//	else if( ( n == -1 ) && ( errno == 104 ) )
//	{
//		WriteFileLog(LERROR,"服务器关闭连接！");
//	}
//	else
//	{
//		WriteFileLog(LERROR,"LiveWire协议通讯错误！");
//	}
//    #else
//	int err = WSAGetLastError();
//	if( err == WSAEWOULDBLOCK ) 
//	{
//		Sleep(1);
//		if( GetTcpClientRun() )
//		{
//			goto again;
//		}
//		else
//		{
//			WriteFileLog(LERROR,"服务器关闭连接！");
//		}
//	}
//	else if( err == WSAESHUTDOWN ) 
//	{
//		WriteFileLog(LERROR,"服务器关闭连接！");
//	}
//	else
//	{
//		WriteFileLog(LERROR,"LiveWire协议通讯错误！");
//	}
//    #endif
//
//	WriteFileLog(LHINT,"LiveWire协议测试客户端已经断开连接！");
//
//	if( hMainWnd )
//	{
//		::SendMessage(hMainWnd,WM_DISCONNECT_DISABLE,0,0); 
//	}
//
//	socketFd = 0;
//
//}
//
//void TcpSocketClientDisplayCallback(int level, char *message)
//{
//	WriteFileLog(__LINE__, __FILE__, level, message);
//}
//
//int LiveWireWrite(const char *str)
//{
//	int   len;
//	char  *src,cz[1024];
//
//	len = strlen(str);
//
//	if( len <= 0 )
//	{
//		WriteFileLog(LERROR,"发送指令：'%s'失败！",str);
//		return(-1);
//	}
//
//	if( ( src = (char *)malloc(len+5) ) == NULL )
//	{
//		WriteFileLog(LERROR,"发送指令：'%s'失败！",str);
//		return(-2);
//	}
//
//	memcpy(src,str,len);
//
//	src[len]   = '\r';
//	src[len+1] = '\n';
//	src[len+2] = '\0';
//
//	if( send(socketFd,src,len+2,0) <= 0 ) 
//	{
//		HexToString(src, strlen(src), cz, 1024);
//		WriteFileLog(LERROR,"发送指令：'%s(%s)'失败！",src,cz);
//		free(src);
//		return(-3);
//	}
//
//	HexToString(src, strlen(src), cz, 1024);
//	WriteFileLog(LHINT,"发送指令：'%s(%s)'",src,cz);
//	free(src);
//	return(len);
//}

//返回  1 : 正常
//返回  0 : 对方关闭连接
//返回 -1 : socket读取错误 
//返回 -2 : 本方关闭连接 
int readchar(int fd,char *ptr,int *loop)
{
	int n;
	again:
	if( ( n = recv(fd, ptr,1,0) ) < 0 )
	{
        #if defined(LINUX)
		if( ( errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN ) )
		{
			if( *loop )
			{
		        usleep(1000);
				goto again;
			}
			else
			{
				return(0);
			}
		}
		else if( ( n == -1 ) && ( errno == 104 ) )
		{
			return(0);
		}
		else
		{
			return(-1);
		}
        #else
		int err = WSAGetLastError();
		if( ( err == WSAEINTR || err == WSAEWOULDBLOCK ) )
		{
			if( *loop )
			{
		        Sleep(1);
				goto again;
			}
			else
			{
				return(0);
			}
		}
		else if( (err == WSAESHUTDOWN) || (err == WSAECONNRESET) ) 
		{
			return(0);
		}
		else
		{
			return(-1);
		}
        #endif
	}
	else if( n == 0 )
	{
		return(0);
	}
	else
	{
		return(1);
	}
}

//返回 >0 : 正常
//返回  0 : 对方关闭连接
//返回 -1 : socket读取错误 
//返回 -2 : 本方关闭连接 
//返回 -3 : 读取的字符串超长 
int readline(int fd,void *buf,int *len,int maxlen,int *loop)  
{
	int  i,rc;
	char c,*ptr;

	ptr = (char *)buf;

	for( i = 0 ; i < maxlen ; i++ ) 
	{
		if( ( rc = readchar(fd,&c,loop) ) == 1 )
		{
			*ptr++ = c;
			if( c == '\n' )
			{
				*ptr = 0;
				*len = i+1;
				return(i+1);
			}
		} 
		else if( rc == 0 ) 
		{
			*ptr = 0;
			*len = i;
			return(0);
		} 
		else
		{
			*ptr = 0;
			*len = i;
			return(-1);
		}
	}

	*ptr = 0;
	*len = i;
	return(-3);
}

//返回 >0 : 正常
//返回  0 : 对方关闭连接
//返回 -1 : socket读取错误 
//返回 -2 : 本方关闭连接 
//返回 -3 : 读取的字符串超长 
int readlineline(int fd,void *buf,int *len,int maxlen,int *loop)
{
	int  i,rc;
	char c,*ptr;
	int  isn = 0;

	ptr = (char *)buf;

	for( i = 0 ; i < maxlen ; i++ ) 
	{
		if( ( rc = readchar(fd,&c,loop) ) == 1 )
		{
			if( c == '\n' )
			{
				if( isn == 1 )
				{
					*ptr = 0;
					*len = i+1;
					return(i+1);
				}
			}
			else if( c == '\r' )
			{
				isn = 1;
			}
			else
			{
				isn = 0;
				*ptr++ = c;
			}
		} 
		else if( rc == 0 ) 
		{
			*ptr = 0;
			*len = i;
			return(0);
		} 
		else
		{
			*ptr = 0;
			*len = i;
			return(-1);
		}
	}
	*ptr = 0;
	*len = i;
	return(-3);
}

//返回 >0 : 正常
//返回  0 : 对方关闭连接
//返回 -1 : socket读取错误 
//返回 -2 : 本方关闭连接 
//返回 -3 : 读取的字符串超长 
int TcpSocketRead(int fd,char *str,int *len,int maxlen,int *loop)
{
	int   ret;
	int   i,len1,*p;
	char  text,src[20];

	memset(&src,0,sizeof(src));

	for(i=0;i<4;i++)
	{
		if( ( ret = readchar(fd,&src[i],loop) ) != 1 )
		{
			*len = 0;
			*str = 0;
			return(ret);
		}
	}

	p = (int *)src;
	len1 = ntohl( *p );

	if( ( len1 < 0 ) || ( len1 > maxlen ) || ( len1 > 20400 ) )
	{
		*len = 0;
		*str = 0;
		return(-3);
	}

	for (i = 0; i < len1; i++)
	{
		if( ( ret = readchar(fd,&text,loop) ) != 1 )
		{
			*len = 0;
			*str = 0;
			return(ret);
		}
		str[i] = text;
	}

	str[len1] = '\0';
	str[len1+1] = '\0';
	*len = len1 ;
	return(*len);
}

//返回 >0 : 发送成功
//返回 -1 : len错误
//返回 -2 : 申请内存失败
//返回 -3 : 发送失败
int TcpSocketWrite(int fd,const char *str,int len)
{
	char  *src;

	if( len <= 0 )
	{
		return(-1);
	}

	if( ( src = (char *)malloc(len+5) ) == NULL )
	{
		return(-2);
	}
	
	int s = htonl(len);
	src[0] = *((char *)&s + 0);
	src[1] = *((char *)&s + 1);
	src[2] = *((char *)&s + 2);
	src[3] = *((char *)&s + 3);
	
	memcpy(src+4,str,len);

	if( send(fd,src,4+len,0) <= 0 ) 
	{
		free(src);
		return(-3);
	}

	free(src);
	return(len);
}


int Tcp_listen(const char *host, const char *serv, socklen_t *addrlenp)
{
	int         listenfd,n;
	const int   on = 1;
	struct addrinfo    hints, *res, *ressave;

	memset(&hints,0,sizeof(struct addrinfo));
	hints.ai_flags = AI_PASSIVE;
	//hints.ai_family = AF_UNSPEC;
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;

	if( (n = getaddrinfo(host, serv, &hints, &res)) != 0 )
	{
		WriteFileLog(LFATAL,"The Tcp_listen function failed, at getaddrinfo, for %s", gai_strerror(n));
		return(-1);
	}

	ressave = res;

	do 
	{
		if( ( listenfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol) ) < 0 )
		{
			continue;        // socket error, try next one 
		}

		if( setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)) < 0 )
		{
			Close(listenfd);
			continue;        // setsockopt error, try next one 
		}

		if (bind(listenfd, res->ai_addr, res->ai_addrlen) == 0)
		{
			//struct sockaddr_in *s;
			//s = (struct sockaddr_in *)res->ai_addr;
			//WriteFileLog(LHINT,"Tcp server listen on %s:%u",inet_ntoa(s->sin_addr),s->sin_port);
			break;           // success 
		}

		Close(listenfd);     // bind error, close and try next one 

	}   while( (res = res->ai_next) != NULL );

	if(res == NULL)          // errno from final socket() or bind() 
	{
		WriteFileLog(LFATAL,"The Tcp_listen function failed, available socket not found.");
		return(-2);
	}

	if( listen(listenfd,10) < 0 )
	{
		WriteFileLog(LFATAL,"The Tcp_listen function failed, on listen : %s", strerror(errno));
		return(-3);
	}

	if( addrlenp )
	{
		*addrlenp = res->ai_addrlen;    // return size of protocol address 
	}

	freeaddrinfo(ressave);

	return(listenfd);
}

int Tcp_connect(const char *host, const char *serv)
{
	int                sockfd, n;
	struct addrinfo    hints, *res, *ressave;

	memset(&hints,0,sizeof(struct addrinfo));
	//hints.ai_family = AF_UNSPEC;
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;

	if( (n = getaddrinfo(host, serv, &hints, &res)) != 0 )
	{
		//WriteFileLog(LFATAL,"The Tcp_connect function failed, at getaddrinfo, for %s", gai_strerror(n));
		return(-1);
	}

	ressave = res;

	do 
	{
		if( ( sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol) ) < 0 )
		{
			continue;        // ignore this one 
		}

		if( connect(sockfd, res->ai_addr, res->ai_addrlen) == 0 )
		{
			break;           // success 
		}

		Close(sockfd);       // ignore this one 

	}   while( ( res = res->ai_next ) != NULL );

	if( res == NULL )        // errno set from final connect() 
	{
		//WriteFileLog(LFATAL,"The Tcp_connect function failed, available connect not found.");
		return(-2);
	}

	freeaddrinfo(ressave);

	return(sockfd);

}

void CloseTCPS(HTCP *tcp)
{
	tcp->loop = 0 ;
}

void *TCPSListenThread(void *param);
void *TCPSConnectThread(void *param);
HTCP *OpenTCPS(const char *name, unsigned short port, TCPCALLBACK tcpcallback, LOGCALLBACK logcallback)
{
	socklen_t addrlen;
	HTCP      *tcps = NULL;
	char      sport[20],cz[1024];
	if( (tcps = (HTCP *)malloc(sizeof(HTCP))) == NULL )
	{
		snprintf(cz,1000,"A memory application error occurred when creating the TCP server(%s).", name);
		if( logcallback != NULL )
		{
			logcallback(LEVEL_ERROR,cz);
		}
		return(0);
	}

	memset(tcps,0,sizeof(HTCP));
	if( ( strlen(name) > 250 ) )
	{
		snprintf(cz,1000,"The name of the TCP server(%s) cannot exceed 250 characters.", name);
		if( logcallback != NULL )
		{
			logcallback(LEVEL_ERROR,cz);
		}
		free(tcps);
		return(0);
	}
	strcpy(tcps->name,name);
	tcps->port = port;
	tcps->tcpcallback = tcpcallback;
	tcps->logcallback = logcallback;
	tcps->loop = 1;
	tcps->connected = 0;
	tcps->fd = 0;

	snprintf(sport,10,"%u", port);
	if( ( tcps->fd = Tcp_listen(NULL,sport, &addrlen) ) < 0 )
	{
		snprintf(cz,1000,"TCP server(%s) failed listen on port %s.", name, sport);
		if( tcps->logcallback != NULL )
		{
			tcps->logcallback(LEVEL_ERROR,cz);
		}
		return(0);
	}
	else
	{
		snprintf(cz,1000,"TCP server(%s) start listen on port %s.", name, sport);
		if( tcps->logcallback != NULL )
		{
			tcps->logcallback(LEVEL_HINT,cz);
		}
	}

	if( SetNonblockSocket(tcps->fd) < 0 )
	{
		snprintf(cz,1000,"TCP server(%s) failed to set up listen non blocking state.", name);
		if( tcps->logcallback != NULL )
		{
			tcps->logcallback(LEVEL_ERROR,cz);
		}
		return(0);
	}

	if( (tcps->thread = CreateThreadWithArg(&TcpServerListenThread, (void *)tcps)) == 0 )
	{
		snprintf(cz,1000,"When the TCP server(%s)  is created, the thread creates an error.", name);
		if( logcallback != NULL )
		{
			logcallback(LEVEL_ERROR,cz);
		}
		free(tcps);
		return(0);
	}

	return(tcps);
}

void *TCPSListenThread(void *param)
{
	socklen_t           len;
	struct sockaddr_in  client;
	char                cz[1024];

	HTCP      *tcps = (HTCP *)param;
	HTCP      *cliarg = NULL;

	while( tcps->loop )
	{
		if( (cliarg = (HTCP *)malloc(sizeof(HTCP))) == NULL )
		{
			snprintf(cz,1000,"When TCP server(%s) receives the client connection, the memory allocation error.", tcps->name);
			if( tcps->logcallback != NULL )
			{
				tcps->logcallback(LEVEL_ERROR,cz);
			}
            #if defined(LINUX)
			sleep(1);
            #else
			Sleep(1000);
            #endif
			continue;
		}

		memset(cliarg,0,sizeof(HTCP));

		len = sizeof(struct sockaddr);

		if( ( cliarg->fd = Accept(tcps->fd, (struct sockaddr *)&client, &len, &(tcps->loop)) ) <= 0 )
		{
			snprintf(cz,1000,"TCP server(%s) accept failure, ignore client connection.", tcps->name);
			if( tcps->logcallback != NULL )
			{
				tcps->logcallback(LEVEL_ERROR,cz);
			}
			free(cliarg);
            #if defined(LINUX)
			usleep(1000);
            #else
			Sleep(1);
            #endif
			continue;
		}

		SetSOLINGEROn(cliarg->fd);
		SetNonblockSocket(cliarg->fd);

		cliarg->tcpcallback = tcps->tcpcallback;
		cliarg->logcallback = tcps->logcallback;
		strcpy(cliarg->name,tcps->name);
		strncpy(cliarg->host,inet_ntoa(client.sin_addr),19);
		cliarg->port = ntohs(client.sin_port);

		if( (CreateThreadWithArg(&TcpServerConnectThread, (void *)cliarg)) == 0 )
		{
			snprintf(cz,1000,"TCP server(%s) connect client(%s:%u) thread failed,  this client socket close.", tcps->name,cliarg->host,cliarg->port);
			if( tcps->logcallback != NULL )
			{
				tcps->logcallback(LEVEL_WARN,cz);
			}
			shutdown(cliarg->fd,2); 
			Close(cliarg->fd);
			free(cliarg);
		}
	}
	Close(tcps->fd);
	snprintf(cz,1000,"TCP server(%s) stop listen on port %u", tcps->name, tcps->port);
	if( tcps->logcallback != NULL )
	{
		tcps->logcallback(LEVEL_HINT,cz);
	}
	return(0);
}

void *TCPSConnectThread(void *param)
{
	HTCP  arg;
	memcpy(&arg,param,sizeof(HTCP));
	free(param);
	param = NULL;

	if( arg.tcpcallback != NULL )
	{
		arg.tcpcallback(arg.name,arg.fd,arg.host,arg.port);
	}

	shutdown(arg.fd,2); 
	Close(arg.fd);
	return(NULL);
}


void CloseTCPC(HTCP *tcpc)
{
	if( tcpc )
	{
		tcpc->loop = 0 ;
		//if( WaitForSingleObject(tcpc->thread, 1000) == WAIT_TIMEOUT )
		//{
		//	TerminateThread(tcpc->thread,0);
		//}
		//CloseHandle(tcpc->thread);
		//free(tcpc);
	}
}

void *TCPCConnectThread(void *param);
HTCP *OpenTCPC(const char *name,const char *host, unsigned short port, TCPCALLBACK tcpcallback, LOGCALLBACK logcallback)
{
	char      cz[1024];
	HTCP      *tcpc = NULL;
	if( (tcpc = (HTCP *)malloc(sizeof(HTCP))) == NULL )
	{
		snprintf(cz,1000,"A memory application error occurred when creating the TCP client(%s).", name);
		if( logcallback != NULL )
		{
			logcallback(LEVEL_ERROR,cz);
		}
		return(0);
	}
	memset(tcpc,0,sizeof(HTCP));
	if( ( strlen(name) > 250 ) )
	{
		snprintf(cz,1000,"The name of the TCP client(%s) cannot exceed 250 characters.", name);
		if( logcallback != NULL )
		{
			logcallback(LEVEL_ERROR,cz);
		}
		free(tcpc);
		return(0);
	}
	strcpy(tcpc->name,name);
	if( ( strlen(host) > 16 ) )
	{
		snprintf(cz,1000,"The host of the TCP client(%s) cannot exceed 16 characters.", name);
		if( logcallback != NULL )
		{
			logcallback(LEVEL_ERROR,cz);
		}
		free(tcpc);
		return(0);
	}
	strcpy(tcpc->host,host);
	tcpc->port = port;
	tcpc->tcpcallback = tcpcallback;
	tcpc->logcallback = logcallback;
	tcpc->loop = 1;
	tcpc->connected = 0;
	tcpc->fd = 0;

	if( (tcpc->thread = CreateThreadWithArg(&TCPCConnectThread, (void *)tcpc)) == 0 )
	{
		snprintf(cz,1000,"When the TCP client(%s)  is created, the thread creates an error.", name);
		if( logcallback != NULL )
		{
			logcallback(LEVEL_ERROR,cz);
		}
		free(tcpc);
		return(0);
	}

	return(tcpc);
}

void *TCPCConnectThread(void *param)
{
	char      sport[20],cz[1024];
	HTCP      *tcps = (HTCP *)param;

	//snprintf(cz,1000,"TCP client(%s) start connect thread.",tcps->name);
	//if( tcps->logcallback != NULL )
	//{
	//	tcps->logcallback(LEVEL_HINT,cz);
	//}

	snprintf(sport,10,"%u",tcps->port);

	while( tcps->loop )
	{
		if( ( tcps->fd = Tcp_connect(tcps->host,sport) ) <= 0 )
		{
			snprintf(cz,1000,"TCP client(%s) connect %s:%s failure.",tcps->name,tcps->host,sport);
			if( tcps->logcallback != NULL )
			{
				tcps->logcallback(LEVEL_ERROR,cz);
			}
            #if defined(LINUX)
			sleep(1);
            #else
			Sleep(1000);
            #endif
			continue;
		}
		//else
		//{
		//	snprintf(cz,1000,"TCP client(%s) connect %s:%s",tcps->name,tcps->host,sport);
		//	if( tcps->logcallback != NULL )
		//	{
		//		tcps->logcallback(LEVEL_HINT,cz);
		//	}
		//}

		tcps->connected = 1;

		SetSOLINGEROn(tcps->fd);
		SetNonblockSocket(tcps->fd);

		if( tcps->tcpcallback != NULL )
		{
			tcps->tcpcallback(tcps->name,tcps->fd,tcps->host,tcps->port);
		}

		shutdown(tcps->fd,2); 
		Close(tcps->fd);
		tcps->connected = 0;

		//snprintf(cz,1000,"TCP client(%s) disconnect %s:%u",tcps->name,tcps->host,tcps->port);
		//if( tcps->logcallback != NULL )
		//{
		//	tcps->logcallback(LEVEL_HINT,cz);
		//}

	}

	//snprintf(cz,1000,"TCP client(%s) end connect thread.",tcps->name);
	//if( tcps->logcallback != NULL )
	//{
	//	tcps->logcallback(LEVEL_HINT,cz);
	//}

    #if defined(LINUX)
	sleep(1);
    #else
	Sleep(1000);
    #endif

	return(0);

}


/*

string to time_t

时间格式 2009-3-24 0:00:08 或 2009-3-24

*/

//int API_StringToTimeEX(char *strDateStr, time_t &timeData)
//
//{
//
//	char *pBeginPos = (char*)strDateStr;
//
//	char *pPos = strstr(pBeginPos, "-");
//
//	if (pPos == NULL)
//
//	{
//
//		//printf("strDateStr[%s] err \n", strDateStr.c_str());
//
//		return -1;
//
//	}
//
//	int iYear = atoi(pBeginPos);
//
//	int iMonth = atoi(pPos + 1);
//
//	pPos = strstr(pPos + 1, "-");
//
//	if (pPos == NULL)
//
//	{
//
//		//printf("strDateStr[%s] err \n", strDateStr.c_str());
//
//		return -1;
//
//	}
//
//	int iDay = atoi(pPos + 1);
//
//	int iHour = 0;
//
//	int iMin = 0;
//
//	int iSec = 0;
//
//	pPos = strstr(pPos + 1, " ");
//
//	//为了兼容有些没精确到时分秒的
//
//	if (pPos != NULL)
//
//	{
//
//		iHour = atoi(pPos + 1);
//
//		pPos = strstr(pPos + 1, ":");
//
//		if (pPos != NULL)
//
//		{
//
//			iMin = atoi(pPos + 1);
//
//			pPos = strstr(pPos + 1, ":");
//
//			if (pPos != NULL)
//
//			{
//
//				iSec = atoi(pPos + 1);
//
//			}
//
//		}
//
//	}
//
//
//
//	struct tm sourcedate;
//
//	memset((void*)&sourcedate,0, sizeof(sourcedate));
//
//	sourcedate.tm_sec = iSec;
//
//	sourcedate.tm_min = iMin;
//
//	sourcedate.tm_hour = iHour;
//
//	sourcedate.tm_mday = iDay;
//
//	sourcedate.tm_mon = iMonth - 1;
//
//	sourcedate.tm_year = iYear - 1900;
//
//	timeData = mktime(&sourcedate);
//
//	return 0;
//
//}
//
//BOOL GetStrFromTime(time_t iTimeStamp, char *pszTime)
//{
//	tm *pTmp = localtime(&iTimeStamp);
//	if (pTmp == NULL)
//	{
//		return FALSE;
//	}
//	sprintf(pszTime, "%d-%d-%d %d:%d:%d", pTmp->tm_year + 1900, pTmp->tm_mon + 1, pTmp->tm_mday, pTmp->tm_hour, pTmp->tm_min, pTmp->tm_sec);
//	return TRUE;
//}


